﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using AFT.Parking.Bizlogic.Malls;
using AFT.Parking.Bizlogic.Parkings;
using AFT.Parking.Entity;
using AFT.Parking.Entity.ArgumentEntity;
using AFT.Parking.Entity.Enums;
using AFT.Parking.Foundation;
using AFT.Parking.WebSite.Common;
using AFT.Parking.WebSite.Filter;
using AFT.Parking.WebSite.Models;

namespace AFT.Parking.WebSite.Controllers
{
    [AdminOnly]
    public class ScanCodeBindingController : BaseController
    {
        private readonly ParkingBiz _parkingBiz;
        private readonly MallLocationBiz _mallLocationBiz;
        public ScanCodeBindingController()
        {
            _parkingBiz = new ParkingBiz();
            _mallLocationBiz = new MallLocationBiz();
        }
        [HttpGet]
        public ActionResult List(PageFilter filter)
        {
            Expression<Func<ScanCodeAndLocation, bool>> exp = u => u.LocationType == (int)LocationTypes.商城;
            if (filter.MallId != 0)
            {
                var mall = _parkingBiz.GetMallArea(filter.MallId);
                if (mall == null)
                    throw new Exception("参数错误");
                ViewBag.Name = mall.Name;
                var locations = _mallLocationBiz.GetStoreList(e => e.MallAreaId == filter.MallId);
                var locationIds = locations.Select(l => l.Id).ToList();
                exp = u => u.LocationType == (int)LocationTypes.商城 && locationIds.Contains(u.LocationId);
            }
            if (filter.LocationId != 0)
            {
                var location = _mallLocationBiz.GetStoreInfo(filter.LocationId);
                if (location == null)
                    throw new Exception("参数错误");
                ViewBag.Name = location.Name;
                exp = u => u.LocationType == (int)LocationTypes.商城 && u.LocationId == filter.LocationId;
            }
            var p = new PaginationParam<ScanCodeAndLocation>
            {
                Expression = exp,
                PageSize = 20,
                PageIndex = filter.Page,
                OrderByList = new List<OrderBy<ScanCodeAndLocation>>
                {
                    new OrderBy<ScanCodeAndLocation> {Sort = false, exp = u => u.Id}
                }
            };
            var list = _parkingBiz.GetScanCodeList(p);

            IPagedList<ScanCodeLocationModel> viewList = new PagedList<ScanCodeLocationModel>
            {
                PageIndex = list.PageIndex,
                PageSize = list.PageSize,
                TotalCount = list.TotalCount,
                TotalPages = list.TotalPages,
                Rows = list.Rows.Select(m => new ScanCodeLocationModel
                {
                    Id = m.Id,
                    LocationId = m.LocationId,
                    LineImg = m.LineImg,
                    ScanCodeTicket = _parkingBiz.GetScanCodeById(m.ScanCodeId).Ticket,
                    ShowTxt = m.ShowTxt,
                }).ToList()
            };
            return View(viewList);
        }
        [HttpGet]
        public ActionResult Add(int locationId)
        {
            if (_mallLocationBiz.GetStoreInfo(locationId) == null)
                throw new Exception("参数错误");
            return View(new ScanCodeAndLocation { LocationId = locationId });
        }


        [HttpPost]
        public ActionResult Add(ScanCodeAndLocation model)
        {
            if (_mallLocationBiz.GetStoreInfo(model.LocationId) == null)
                throw new Exception("参数错误");
            var scanCode = _parkingBiz.GetScanCodeNotUse();
            if (scanCode == null)
            {
                ViewBag.Message = "二维码已全部使用完，请联系管理员或稍后重试";
                return View(model);
            }

            model.ScanCodeId = scanCode.Id;
            model.LocationType = (int)LocationTypes.商城;
            //model.LineImg = UpdateImageUrl(model.LineImg);
            _parkingBiz.AddScanCodeAndLocation(model);
            ViewBag.Message = "保存成功";
            return View(model);
        }


        [HttpGet]
        public ActionResult Edit(int id, int locationId)
        {
            var rel = _parkingBiz.GetScancodeAndLocation(e => e.Id == id);
            if (rel == null)
                throw new Exception("参数错误");
            ViewData["AllMallLinePoint"] = new SelectList(_parkingBiz.GetPointsList(id), "id", "name");// MallLinePointsToList();
            ViewData["Sort"] = new SelectList(new List<MallLinePoint>(), "id", "name");// MallLinePointsToList(null);
            return View(rel);
        }
        [HttpPost]
        public ActionResult Edit(ScanCodeAndLocation model, List<int> Sort)
        {
            var rel = _parkingBiz.GetScancodeAndLocation(e => e.Id == model.Id);
            if (rel == null)
                throw new Exception("参数错误");

            if (rel.LineImg != model.LineImg)
                rel.LineImg = UpdateImageUrl(model.LineImg);
            rel.ShowTxt = model.ShowTxt;
           _parkingBiz.SortPonit(Sort);
            _parkingBiz.UpdateScanCodeAndLocation(rel);
            ViewData["AllMallLinePoint"] = new SelectList(_parkingBiz.GetPointsList(model.Id), "id", "name");// MallLinePointsToList();
            ViewData["Sort"] = new SelectList(new List<MallLinePoint>(), "id", "name");// MallLinePointsToList(null);
            ViewBag.Message = "保存成功";
            return View(model);
        }

        public ActionResult Delete(int id)
        {
            _parkingBiz.DeleteScanCodeAndLocation(id);
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        public ActionResult FileUpLoadFile()
        {
            return Json(FileHelper.Upload("Locations"), "application/json", JsonRequestBehavior.AllowGet);
        }
        private string UpdateImageUrl(string tempImg)
        {
            return FileHelper.Save("Locations", tempImg);
        }

        #region Line Pionts
        /// <summary>
        /// 计算坐标点在图上的位置
        /// </summary>
        /// <param name="id">scancodeAndLocation.id</param>
        /// <returns></returns>
        public ActionResult CheckLocations(int id,int locationId)
        {
            string imgSrc = ConstFields.DefaultImage;
            var scancodeAndLocation = _parkingBiz.GetScancodeAndLocation(u => u.Id == id);
            var mallLocation = _mallLocationBiz.GetStoreInfo(locationId);
            if (scancodeAndLocation != null && mallLocation != null)
            {
                var mallArea = _mallLocationBiz.GetMallArea(mallLocation.MallAreaId);
                if (mallArea != null && !string.IsNullOrEmpty(mallArea.ImgUrl))
                {
                    string ImgUrl = mallArea.ImgUrl;
                    var mallPoints =
                        _mallLocationBiz.GetLinePoints(scancodeAndLocation.Id).OrderBy(u => u.Sort).ToList();
                    if (mallPoints.Count > 0)
                    {
                        mallPoints.Add(new MallLinePoint()
                        {
                            LocationX = (int) mallLocation.LocationX,
                            LocationY = (int) mallLocation.LocationY
                        });
                        for (int i = 0; i < mallPoints.Count - 1; i++)
                        {
                            string returnImg = Common.FileHelper.DrawDashOrArrow(ImgUrl, mallPoints[i].LocationX,
                                mallPoints[i].LocationY,
                                mallPoints[i+1].LocationX, mallPoints[i+1].LocationY, false, true);
                            if (i != 0)
                            {
                                if (System.IO.File.Exists(Server.MapPath(string.Format(ImgUrl, ""))))
                                    System.IO.File.Delete(Server.MapPath(string.Format(ImgUrl, "")));
                            }
                            ImgUrl = string.Format(returnImg, "");
                        }
                        imgSrc = ImgUrl;
                    }
                }
            }
            ViewBag.Img = imgSrc;
            return View();
        }

        public ActionResult AddLinePoint(int scanCodeAndLocationId, int mallLocationId)
        {
            var rel = _parkingBiz.GetScancodeAndLocation(e => e.Id == scanCodeAndLocationId);
            if (rel == null)
                throw new Exception("参数错误");
            return View(new MallLinePoint { MallLocationId = mallLocationId, ScanCodeAndLocationId = scanCodeAndLocationId });
        }

        [HttpPost]
        public ActionResult AddLinePoint(MallLinePoint mallLinePoint)
        {
            var rel = _parkingBiz.GetScancodeAndLocation(e => e.Id == mallLinePoint.ScanCodeAndLocationId);
            if (rel == null)
                throw new Exception("参数错误");
            _parkingBiz.AddMallLinePoint(mallLinePoint);
            return View(mallLinePoint);
        }

        #endregion
    }
}